package com.test.dao.impl;

import java.util.HashMap;
import java.util.Map;

import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.mongodb.BasicDBObject;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.test.dao.AccountDao;
import com.test.dto.account.RegisterDto;
import com.test.utils.JsonUtil;
import com.test.utils.MongoFactory;

@Repository
public class AccountDaoImpl implements AccountDao {
	@Autowired
	private MongoFactory MongoFactory;

	@Override
	public Document findUserByUsername(String username) {
		BasicDBObject filter = new BasicDBObject("username", username);
		FindIterable<Document> iter = getUserCollection().find(filter);
		return iter.first();
	}
	
	@Override
	public void register(RegisterDto registerDto) {
		Document document = Document.parse(JsonUtil.obj2Json(registerDto));
		getUserCollection().insertOne(document);
	}

	@Override
	public void updateUserToken(ObjectId id, String token) {
		BasicDBObject filter = new BasicDBObject();
		filter.put("_id", id);
		BasicDBObject update = new BasicDBObject();
		update.put("$set", new BasicDBObject("token", token));
		getUserCollection().updateOne(filter, update);
	}
	
	private MongoCollection<Document> getUserCollection() {
		return MongoFactory.getDb().getCollection("user");
	}

}
